package com.edu.gdkm.filter;

import com.edu.gdkm.util.cookiesUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
* 管理员上次登录时间功能
* */
@WebFilter("/adminServlet")
public class lastTimeFilter implements Filter {

	private cookiesUtil cookiesUtil;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		cookiesUtil = new cookiesUtil();
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		HttpServletResponse resp = (HttpServletResponse) servletResponse;

		String lastTime;
		Cookie lastTimeCookie = cookiesUtil.findCookie(req.getCookies(), "dyp_last-time");
		/* 判断是否首次登录 */
		if (lastTimeCookie != null){
			lastTime = URLDecoder.decode(
					lastTimeCookie.getValue(), "UTF-8");
		} else {
			lastTime = "首次登录";
		}
		/* 获取当前登录时间 */
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Cookie cookie = new Cookie(
				"dyp_last-time",
				URLEncoder.encode(
						sdf.format(new Date()), "UTF-8"));
		cookie.setMaxAge(60*60*24*360);
		resp.addCookie(cookie);
		/* 会话域存储 */
		req.getSession().setAttribute("lastTime", lastTime);
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void destroy() {

	}
}
